/**
 * 通知公告相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取通知公告列表
 * @param {object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.keyword - 搜索关键词
 * @param {number} params.type - 通知类型
 * @param {number} params.status - 发布状态
 * @returns {Promise} 通知公告列表
 */
export const getNoticeList = (params = {}) => {
  return request.get('/notice/list', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '', type, status } = queryParams
    
    // 模拟通知公告数据
    const mockNotices = Array.from({ length: 60 }, (_, index) => ({
      id: index + 1,
      title: `通知公告${index + 1}`,
      type: Math.floor(Math.random() * 4) + 1, // 1-4
      typeName: ['政务通知', '教育培训', '意见征集', '公示公告'][Math.floor(Math.random() * 4)],
      status: Math.floor(Math.random() * 3) + 1, // 1-3
      statusName: ['草稿', '已发布', '已下线'][Math.floor(Math.random() * 3)],
      summary: `这是第${index + 1}个通知公告的摘要信息`,
      content: `这是第${index + 1}个通知公告的详细内容，包含了重要的信息和说明。`,
      author: `发布人${Math.floor(Math.random() * 10) + 1}`,
      department: ['办公室', '人事部', '财务部', '业务部', '技术部'][Math.floor(Math.random() * 5)],
      priority: Math.floor(Math.random() * 3) + 1, // 1-3
      priorityName: ['普通', '重要', '紧急'][Math.floor(Math.random() * 3)],
      isTop: Math.random() > 0.8,
      viewCount: Math.floor(Math.random() * 1000),
      likeCount: Math.floor(Math.random() * 100),
      commentCount: Math.floor(Math.random() * 50),
      publishTime: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() : null,
      expireTime: Math.random() > 0.5 ? new Date(Date.now() + Math.random() * 60 * 24 * 60 * 60 * 1000).toISOString() : null,
      createTime: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString(),
      attachments: Math.random() > 0.7 ? [
        { name: '附件文件.pdf', url: '/files/attachment.pdf', size: 1024000 }
      ] : []
    }))
    
    // 过滤数据
    let filteredNotices = mockNotices
    if (keyword) {
      filteredNotices = mockNotices.filter(notice => 
        notice.title.includes(keyword) || 
        notice.summary.includes(keyword) ||
        notice.content.includes(keyword)
      )
    }
    if (type) {
      filteredNotices = filteredNotices.filter(notice => notice.type === Number(type))
    }
    if (status) {
      filteredNotices = filteredNotices.filter(notice => notice.status === Number(status))
    }
    
    // 排序：置顶优先，然后按发布时间倒序
    filteredNotices.sort((a, b) => {
      if (a.isTop && !b.isTop) return -1
      if (!a.isTop && b.isTop) return 1
      return new Date(b.publishTime || b.createTime) - new Date(a.publishTime || a.createTime)
    })
    
    // 分页
    const total = filteredNotices.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredNotices.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取通知公告详情
 * @param {number} id - 通知ID
 * @returns {Promise} 通知详情
 */
export const getNoticeDetail = (id) => {
  return request.get(`/notice/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      title: `通知公告${id}`,
      type: 1,
      typeName: '政务通知',
      status: 2,
      statusName: '已发布',
      summary: '这是一个重要的政务通知摘要',
      content: `
        <h2>重要通知</h2>
        <p>这是第${id}个通知公告的详细内容。</p>
        <p>请各部门认真学习贯彻，确保工作顺利开展。</p>
        <h3>主要内容：</h3>
        <ul>
          <li>第一项重要内容</li>
          <li>第二项重要内容</li>
          <li>第三项重要内容</li>
        </ul>
        <h3>执行要求：</h3>
        <ol>
          <li>各部门要高度重视</li>
          <li>制定具体实施方案</li>
          <li>确保按时完成任务</li>
        </ol>
        <p>特此通知。</p>
      `,
      author: '管理员',
      authorId: 1,
      department: '办公室',
      priority: 2,
      priorityName: '重要',
      isTop: true,
      viewCount: 1250,
      likeCount: 89,
      commentCount: 23,
      publishTime: '2024-01-15T10:00:00.000Z',
      expireTime: '2024-03-15T23:59:59.000Z',
      createTime: '2024-01-14T16:00:00.000Z',
      updateTime: '2024-01-15T10:00:00.000Z',
      attachments: [
        {
          id: 1,
          name: '通知附件.pdf',
          originalName: '重要通知附件.pdf',
          url: '/files/notice-attachment.pdf',
          size: 2048000,
          downloadCount: 156,
          uploadTime: '2024-01-14T16:30:00.000Z'
        },
        {
          id: 2,
          name: '实施方案.docx',
          originalName: '具体实施方案.docx',
          url: '/files/implementation-plan.docx',
          size: 1536000,
          downloadCount: 89,
          uploadTime: '2024-01-14T17:00:00.000Z'
        }
      ],
      tags: ['重要', '政务', '通知'],
      relatedNotices: [
        { id: 2, title: '相关通知1', publishTime: '2024-01-10T10:00:00.000Z' },
        { id: 3, title: '相关通知2', publishTime: '2024-01-12T14:00:00.000Z' }
      ]
    })
  })
}

/**
 * 创建通知公告
 * @param {object} data - 通知数据
 * @returns {Promise} 创建结果
 */
export const createNotice = (data) => {
  return request.post('/notice', data, {}, (params) => {
    const { title, type, content, summary } = params
    
    if (!title || !type || !content) {
      return mockError('请填写完整的通知信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      ...params,
      status: 1,
      statusName: '草稿',
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }, '通知公告创建成功')
  })
}

/**
 * 更新通知公告
 * @param {number} id - 通知ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateNotice = (id, data) => {
  return request.put(`/notice/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '通知公告更新成功')
  })
}

/**
 * 删除通知公告
 * @param {number} id - 通知ID
 * @returns {Promise} 删除结果
 */
export const deleteNotice = (id) => {
  return request.delete(`/notice/${id}`, {}, () => {
    return mockSuccess(null, '通知公告删除成功')
  })
}

/**
 * 批量删除通知公告
 * @param {Array} ids - 通知ID数组
 * @returns {Promise} 删除结果
 */
export const batchDeleteNotices = (ids) => {
  return request.delete('/notice/batch', { ids }, () => {
    return mockSuccess(null, `成功删除${ids.length}条通知公告`)
  })
}

/**
 * 发布通知公告
 * @param {number} id - 通知ID
 * @returns {Promise} 发布结果
 */
export const publishNotice = (id) => {
  return request.put(`/notice/${id}/publish`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      status: 2,
      statusName: '已发布',
      publishTime: new Date().toISOString()
    }, '通知公告发布成功')
  })
}

/**
 * 下线通知公告
 * @param {number} id - 通知ID
 * @returns {Promise} 下线结果
 */
export const unpublishNotice = (id) => {
  return request.put(`/notice/${id}/unpublish`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      status: 3,
      statusName: '已下线'
    }, '通知公告下线成功')
  })
}

/**
 * 置顶/取消置顶通知公告
 * @param {number} id - 通知ID
 * @param {boolean} isTop - 是否置顶
 * @returns {Promise} 操作结果
 */
export const toggleNoticeTop = (id, isTop) => {
  return request.put(`/notice/${id}/top`, { isTop }, {}, () => {
    return mockSuccess({
      id: Number(id),
      isTop
    }, isTop ? '通知公告置顶成功' : '通知公告取消置顶成功')
  })
}

/**
 * 点赞/取消点赞通知公告
 * @param {number} id - 通知ID
 * @returns {Promise} 点赞结果
 */
export const likeNotice = (id) => {
  return request.post(`/notice/${id}/like`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      liked: true,
      likeCount: Math.floor(Math.random() * 100) + 50
    }, '点赞成功')
  })
}

/**
 * 获取通知公告评论
 * @param {number} id - 通知ID
 * @param {object} params - 查询参数
 * @returns {Promise} 评论列表
 */
export const getNoticeComments = (id, params = {}) => {
  return request.get(`/notice/${id}/comments`, params, {}, (queryParams) => {
    const { page = 1, pageSize = 20 } = queryParams
    
    const mockComments = Array.from({ length: 45 }, (_, index) => ({
      id: index + 1,
      noticeId: Number(id),
      content: `这是第${index + 1}条评论内容`,
      userName: `用户${index + 1}`,
      userAvatar: `/avatars/user${(index % 10) + 1}.jpg`,
      likeCount: Math.floor(Math.random() * 20),
      replyCount: Math.floor(Math.random() * 5),
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      replies: index < 3 ? Array.from({ length: Math.floor(Math.random() * 3) + 1 }, (_, replyIndex) => ({
        id: replyIndex + 1,
        commentId: index + 1,
        content: `这是回复${replyIndex + 1}`,
        userName: `回复用户${replyIndex + 1}`,
        userAvatar: `/avatars/user${(replyIndex % 10) + 1}.jpg`,
        createTime: new Date(Date.now() - Math.random() * 20 * 24 * 60 * 60 * 1000).toISOString()
      })) : []
    }))
    
    // 分页
    const total = mockComments.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = mockComments.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 添加通知公告评论
 * @param {number} id - 通知ID
 * @param {object} data - 评论数据
 * @returns {Promise} 评论结果
 */
export const addNoticeComment = (id, data) => {
  return request.post(`/notice/${id}/comments`, data, {}, (params) => {
    const { content } = params
    
    if (!content || content.trim().length === 0) {
      return mockError('评论内容不能为空', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      noticeId: Number(id),
      content: content.trim(),
      userName: '当前用户',
      userAvatar: '/avatars/current-user.jpg',
      likeCount: 0,
      replyCount: 0,
      createTime: new Date().toISOString()
    }, '评论发表成功')
  })
}

/**
 * 回复通知公告评论
 * @param {number} id - 通知ID
 * @param {number} commentId - 评论ID
 * @param {object} data - 回复数据
 * @returns {Promise} 回复结果
 */
export const replyNoticeComment = (id, commentId, data) => {
  return request.post(`/notice/${id}/comments/${commentId}/reply`, data, {}, (params) => {
    const { content } = params
    
    if (!content || content.trim().length === 0) {
      return mockError('回复内容不能为空', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      commentId: Number(commentId),
      content: content.trim(),
      userName: '当前用户',
      userAvatar: '/avatars/current-user.jpg',
      createTime: new Date().toISOString()
    }, '回复发表成功')
  })
}

/**
 * 上传通知公告附件
 * @param {number} id - 通知ID
 * @param {FormData} formData - 文件数据
 * @returns {Promise} 上传结果
 */
export const uploadNoticeAttachment = (id, formData) => {
  return request.upload(`/notice/${id}/attachments`, formData, {}, () => {
    return mockSuccess({
      id: Date.now(),
      noticeId: Number(id),
      name: 'attachment.pdf',
      originalName: '附件文件.pdf',
      url: '/files/attachment.pdf',
      size: 1024000,
      downloadCount: 0,
      uploadTime: new Date().toISOString()
    }, '附件上传成功')
  })
}

/**
 * 删除通知公告附件
 * @param {number} id - 通知ID
 * @param {number} attachmentId - 附件ID
 * @returns {Promise} 删除结果
 */
export const deleteNoticeAttachment = (id, attachmentId) => {
  return request.delete(`/notice/${id}/attachments/${attachmentId}`, {}, () => {
    return mockSuccess(null, '附件删除成功')
  })
}

/**
 * 下载通知公告附件
 * @param {number} id - 通知ID
 * @param {number} attachmentId - 附件ID
 * @returns {Promise} 下载结果
 */
export const downloadNoticeAttachment = (id, attachmentId) => {
  return request.get(`/notice/${id}/attachments/${attachmentId}/download`, {}, { responseType: 'blob' }, () => {
    return mockSuccess({
      url: '/files/attachment.pdf',
      filename: '附件文件.pdf'
    })
  })
}

/**
 * 获取通知公告统计数据
 * @param {object} params - 查询参数
 * @returns {Promise} 统计数据
 */
export const getNoticeStats = (params = {}) => {
  return request.get('/notice/stats', params, {}, () => {
    return mockSuccess({
      total: 156,
      published: 128,
      draft: 23,
      offline: 5,
      totalViews: 15680,
      totalLikes: 1234,
      totalComments: 567,
      monthlyStats: Array.from({ length: 12 }, (_, index) => ({
        month: index + 1,
        published: Math.floor(Math.random() * 20) + 5,
        views: Math.floor(Math.random() * 2000) + 500,
        likes: Math.floor(Math.random() * 200) + 50,
        comments: Math.floor(Math.random() * 100) + 20
      })),
      typeStats: [
        { type: 1, typeName: '政务通知', count: 45, percentage: 28.8 },
        { type: 2, typeName: '教育培训', count: 38, percentage: 24.4 },
        { type: 3, typeName: '意见征集', count: 35, percentage: 22.4 },
        { type: 4, typeName: '公示公告', count: 38, percentage: 24.4 }
      ],
      popularNotices: Array.from({ length: 10 }, (_, index) => ({
        id: index + 1,
        title: `热门通知${index + 1}`,
        viewCount: Math.floor(Math.random() * 1000) + 500,
        likeCount: Math.floor(Math.random() * 100) + 50,
        publishTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
      }))
    })
  })
}